<template>
  <div>
    <el-card shadow="never" :body-style="{ padding: '10px' }">
      <!-- 卡片头部 -->
      <div slot="header">
        <el-button type="text" size="medium" plain icon="el-icon-back" @click="goBack" 
          >返回上一页面</el-button
        >
        <el-divider direction="vertical"></el-divider>
        题库标题：<span class="head-font">{{ title }}</span>
        <el-divider direction="vertical"></el-divider>
        题目总数：<span class="head-font">{{ totalNum }}</span>
      </div>
      <!-- 表格上方按钮 -->
      <div>
        <div style="float: left; margin-bottom: 10px">
          <el-dropdown>
            <el-button type="primary" plain size="mini"
              >新增题目<i class="el-icon-arrow-down el-icon--right"></i
            ></el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="addRadio()"
                >单选题</el-dropdown-item
              >
              <el-dropdown-item @click.native="addCheckbox()"
                >多选题</el-dropdown-item
              >
              <el-dropdown-item @click.native="addToF()"
                >判断题</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
          <!-- 批量导入 -->
          <el-button
            type="primary"
            plain
            icon="el-icon-upload"
            size="mini"
            @click="batchImportQuestions"
            >批量导入</el-button
          >
          <el-button
            type="danger"
            plain
            icon="el-icon-delete"
            size="mini"
            @click="deleteList"
            >批量删除</el-button
          >
        </div>
        <div style="float: right">
          <el-tooltip class="item" effect="dark" content="刷新" placement="top">
            <el-button
              size="mini"
              circle
              icon="el-icon-refresh"
              @click="queryList()"
            />
          </el-tooltip>
        </div>
      </div>
      <!-- 信息列表 -->
      <div style="float: left; width: 100%">
        <el-table
          border
          v-loading="listLoading"
          :header-cell-style="{ background: '#FAFAFA' }"
          :data="questionList"
          @selection-change="handleSelectionChange"
          height="750px"
          style="width: 100%"
        >
          <el-table-column type="selection" width="55"> </el-table-column>
          <el-table-column type="index" width="55"> </el-table-column>
          <el-table-column
            prop="id"
            label="id"
            width="150"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column prop="type" label="题型" width="100">
            <!-- <template slot-scope="scope">
              <span v-show="scope.row.type == '单选'">单选题</span>
              <span v-show="scope.row.type == '多选'">多选题</span>
              <span v-show="scope.row.type == '判断'">判断题</span>
            </template> -->
          </el-table-column>
          <el-table-column
            prop="question"
            label="题干"
            :show-overflow-tooltip="true"
          >
          </el-table-column>
          <el-table-column prop="correct" label="答案" width="180">
          </el-table-column>
          <el-table-column prop="gmtCreate" label="创建时间" width="180">
          </el-table-column>
          <el-table-column prop="gmtModified" label="最后修改时间" width="180">
          </el-table-column>
          <el-table-column
            fixed="right"
            label="操作"
            width="180"
            align="center"
          >
            <template slot-scope="scope">
              <el-button size="medium" type="text" @click="preview(scope.row)">
                详情
              </el-button>
              <el-button size="medium" type="text" @click="edit(scope.row)">
                编辑
              </el-button>
              <el-button
                size="medium"
                type="text"
                @click="deleteOne(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <!-- 题目详情 -->
    <el-dialog title="题目详情" :visible.sync="previewDialog" width="30%">
      <el-row>{{ questionInfo.question }}</el-row>
      <div style="line-height: 1.8">
        <el-row :key="index" v-for="(item, index) in questionInfo.opt">
          <span>{{ String.fromCharCode(65 + index) }}</span>
          <span>{{ item }}</span>
        </el-row>
        <el-divider></el-divider>
        <el-row
          >答案：
          <span :key="item.id" v-for="item in questionInfo.correct">
            <span v-html="item"></span></span
        ></el-row>
        <el-divider></el-divider>
        <el-row
          >解析：<span v-if="questionInfo.analysis == ''">暂无解析</span
          ><span v-else>{{ questionInfo.analysis }}</span></el-row
        >
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="previewDialog = false">取 消</el-button>
        <el-button type="primary" @click="previewDialog = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <!-- 新增或编辑题目 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="formDialog"
      width="30%"
      :before-close="handleClose"
    >
      <el-form ref="form" :rules="rules" :model="form" label-width="100px">
        <el-form-item label="题干：" prop="question">
          <el-input v-model="form.question" type="textarea"></el-input>
        </el-form-item>
        <el-form-item label="选项：" prop="opt">
          <el-form-item
            v-for="(item, index) in form.opt"
            :key="index"
            :label="String.fromCharCode(65 + index)"
            label-width="30px"
            class="options"
          >
            <el-input v-model="form.opt[index]" style="width: 85%" />
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              plain
              v-show="form.type != '判断'"
              @click="removeOption(index)"
            ></el-button>
          </el-form-item>
        </el-form-item>
        <!-- 多选答案 -->
        <el-form-item
          label="正确答案："
          prop="correct"
          v-show="form.type == '多选'"
        >
          <el-checkbox-group v-model="form.correct">
            <el-checkbox
              v-for="(item, index) in form.opt"
              :key="index"
              :label="String.fromCharCode(65 + index)"
              >{{ String.fromCharCode(65 + index) }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <!-- 单选答案 -->
        <el-form-item label="正确答案：" v-show="form.type != '多选'">
          <el-radio-group v-model="otherAnswer">
            <el-radio
              v-for="(item, index) in form.opt"
              :key="index"
              :label="String.fromCharCode(65 + index)"
              >{{ String.fromCharCode(65 + index) }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="解析：">
          <el-input type="textarea" v-model="form.analysis"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          type="success"
          @click="addOption"
          v-show="form.type != '判断'"
          >添加选项</el-button
        >
        <el-button @click="formDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </span>
    </el-dialog>
    <!-- 通过上传excel批量导入题目 -->
    <el-dialog
      :title="upload.title"
      :visible.sync="batchImportDialog"
      width="400px"
      append-to-body
    >
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-error="handleFileError"
        :on-exceed="handleFileExceed"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span><h3>仅允许导入xls、xlsx格式文件。请预先下载模板！</h3></span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 15px; vertical-align: baseline"
            href="https://school-file-mjzx.oss-cn-guangzhou.aliyuncs.com/ExcelTemplate/batchImportQuestionsTemplate.xlsx"
            >下载题目模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBatchImportForm"
          >确 定</el-button
        >
        <el-button @click="batchImportDialog = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  addQuestion,
  deleteQuestion,
  updateQuestion,
  queryQuestion,
} from "@/api/question";
export default {
  //试题列表
  name: "Question",
  data: function () {
    return {
      //表格加载遮罩
      listLoading: "false",
      //试卷编号
      testPaperId: this.$route.query.id,
      //试卷标题
      title: this.$route.query.title,
      //题目总数
      totalNum: "",
      //题目列表
      questionList: [],
      //预览对话框
      previewDialog: false,
      //批量导入题目对话框
      batchImportDialog: false,
      //批量导入题目的配置
      upload: {
        title: "批量导入题目",
        url:
          process.env.BASE_API +
          "/eduM2/eduTest/batchImportQuestion/" +
          this.$route.query.id,
        isUploading: false,
      },
      //题目预览信息
      questionInfo: "",
      //批量删除列表
      selectList: "",
      //对话框标题
      dialogTitle: "",
      //新增题目的题型
      addType: "",
      //新增或编辑题目的对话框
      formDialog: false,
      //判断当前是新增题目还是编辑题目
      addOrEdit: "",
      //单选题和判断题答案绑定
      otherAnswer: "A",
      //新增表单
      form: {},
      //表单验证
      rules: {
        question: [
          { required: true, message: "题干不能为空", trigger: "blur" },
        ],
        correct: [
          {
            type: "array",
            required: true,
            message: "请至少选择一个答案",
            trigger: "change",
          },
        ],
      },
    };
  },
  created: function () {
    this.queryList();
  },
  methods: {
    //根据试卷编号查找的题目列表
    queryList() {
      let that = this;
      this.listLoading = true;
      queryQuestion(this.testPaperId).then((res) => {
        that.totalNum = res.data.total;
        that.questionList = res.data.resList;
        this.listLoading = false;
      });
    },
    //预览
    preview(question) {
      this.questionInfo = question;
      this.previewDialog = true;
    },
    //题目编辑
    edit(question) {
      this.dialogTitle = "编辑题目";
      this.addOrEdit = "edit";
      this.form = question;
      if (question.type != "多选") {
        //非多选对应的v-model
        this.otherAnswer = question.correct[0];
      }
      this.formDialog = true;
    },
    //删除单个题目
    deleteOne(question) {
      var self = this;
      this.$confirm("此操作将删除该题目, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var idArray = []; //删除列表
          idArray.push(question.id);
          self.deleteAjax(idArray);
        })
        .catch(() => {});
    },
    //选择删除的id列表
    handleSelectionChange: function (val) {
      this.selectList = val;
    },
    //批量删除题目
    deleteList() {
      var self = this;
      if (this.selectList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("此操作将删除选中的所有题目, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var idArray = [];
          self.selectList.forEach(function (question) {
            idArray.push(question.id);
          });
          self.deleteAjax(idArray);
        })
        .catch(() => {});
    },
    //删除的Ajax请求
    deleteAjax: function (idArray) {
      var that = this;
      deleteQuestion(idArray).then((res) => {
        if (res.success == true) {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          that.queryList();
        } else {
          this.$message({
            message: "删除失败",
            type: "error",
          });
        }
      });
    },
    //新增单选题
    addRadio() {
      this.dialogTitle = "新增单选题";
      this.addOrEdit = "add";
      this.resetForm();
      this.form.type = "单选";
      this.form.opt = ["", "", "", ""];
      this.formDialog = true;
    },
    //新增多选题
    addCheckbox() {
      this.dialogTitle = "新增多选题";
      this.addOrEdit = "add";
      this.resetForm();
      this.form.type = "多选";
      this.form.opt = ["", "", "", "", ""];
      this.form.correct = [];
      this.formDialog = true;
    },
    //新增判断题
    addToF() {
      this.dialogTitle = "新增判断题";
      this.addOrEdit = "add";
      this.resetForm();
      this.form.type = "判断";
      this.form.opt = ["正确", "错误"];
      this.formDialog = true;
    },
    //添加选项
    addOption() {
      this.form.opt.push("");
    },
    //删除选项
    removeOption(index) {
      if (index > 2) {
        this.form.opt.splice(index, 1);
        this.form.correct = [];
      } else {
        this.$message({
          message: "选项的个数不能少于三条",
          type: "warning",
        });
      }
    },
    //提交表单（新增或编辑）
    submitForm() {
      if (this.form.type != "多选") {
        this.form.correct = [];
        this.form.correct.push(this.otherAnswer);
      }
      let that = this;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (that.addOrEdit == "add") {
            //新增
            addQuestion(that.form).then((res) => {
              if (res.success == true) {
                this.$message({
                  message: "提交成功",
                  type: "success",
                });
                that.queryList();
                that.formDialog = false;
              } else {
                this.$message({
                  message: "提交失败",
                  type: "error",
                });
              }
            });
          } else {
            //编辑
            let editForm = {
              id: that.form.id,
              question: that.form.question,
              opt: that.form.opt,
              correct: that.form.correct,
              analysis: that.form.analysis,
            };
            console.log(editForm);
            updateQuestion(editForm).then((res) => {
              if (res.success == true) {
                this.$message({
                  message: "提交成功",
                  type: "success",
                });
                that.queryList();
                that.formDialog = false;
              } else {
                this.$message({
                  message: "提交失败",
                  type: "error",
                });
              }
            });
          }
        } else {
          console.log("提交失败");
          return false;
        }
      });
    },
    //批量导入题目
    batchImportQuestions() {
      this.batchImportDialog = true;
    },
    //上传文件失败
    handleFileError() {
      this.$message({
        message: "上传失败",
        type: "error",
      });
    },
    //上传文件超出1个限制
    handleFileExceed() {
      this.$message({
        message: "上传文件个数超出限制，最多上传1个文件",
        type: "warning",
      });
    },
    //提交批量导入题目的表单
    submitBatchImportForm() {
      this.submitFileForm();
    },
    //上传文件
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    //上传成功
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false;
      if (response.success == true) {
        this.$message({
          message: "上传成功",
          type: "success",
        });
        this.batchImportDialog = false;
        this.queryList();
      } else {
        this.$message({
          message: "上传失败",
          type: "error",
        });
      }
    },
    //提交上传文件的表单
    submitFileForm() {
      this.$refs.upload.submit();
    },

    //重置新增的表单
    resetForm() {
      this.form = {
        testId: this.$route.query.id,
        question: "",
        opt: [],
        correct: [],
        analysis: "",
        type: "",
      };
      this.otherAnswer = "A";
      if (this.$refs["form"] !== undefined) {
        //如果是第一次就点击新增就不用reset
        this.$refs["form"].resetFields();
      }
    },
    //返回
    goBack() {
      this.$router.go(-1);
    },
    //关闭对话框的提示框
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
  },
};
</script>
<style scoped>
.head-font {
  font-weight: bold;
}
.options {
  margin-bottom: 10px;
}
</style>